#include "Cats/CatStates/CatState.h"
#include "Cats/CatStates/CatState_Base_Attack.h"
#include "Cats/BaseCat.h"
#include "Cats/CatSpriteLoader.h"
#include "Character/Character.h"

#include "SimpleAudioEngine.h"

CatState_Base_Attack::CatState_Base_Attack(BaseCat* pCatRef):CatState(pCatRef)
{
	_exitState = false;
	_cameFromFlankState = false;
}

CatState_Base_Attack::~CatState_Base_Attack()
{

}

void CatState_Base_Attack::runOnEnter()
{
	// Attack Sound
	//CocosDenshion::SimpleAudioEngine::sharedEngine()->playEffect("Game/Sound/Cat_Attack.wav");

	//play attack animation
	_pCatRef->stopActionByTag(CatSpriteLoader::SPRITE_CAT_TAG);
	_pCatRef->runAction(CatSpriteLoader::getCatAnimation(_pCatRef->getCatType(), CAT_ANIM_ATTACK));

	//check if came from flank state, to reduce flank attack speed
	if (_pCatRef->getPreviousCatState() == CAT_FLANK)
		_cameFromFlankState = true;

}

void CatState_Base_Attack::update(float timeDiff)
{
	if (!_exitState)
	{
		//move quickly towards the character's position (homing)
		//cat attack speed
		float speed = (_pCatRef->getAttackSpeedX() * timeDiff) * _pCatRef->getSpeedMultiplier();

		//reduce speed if its from flank
		if (_cameFromFlankState)
			speed /= FLANK_ATK_SPEED_MULTIPLIER;

		//homing direction
		float targetX = _pCharRef->getPositionX() - _pCatRef->getPositionX();
		float targetY = _pCharRef->getPositionY() - _pCatRef->getPositionY();
		float rotation = atan2(targetY, targetX) * 180 / 3.14159;

		//MATH for proportionately correct X, Y speed
		float newX = speed * (90 - abs(rotation)) / 90;
		float newY;
		if(rotation < 0)
			newY = -speed + abs(newX);
		else
			newY = speed - abs(newX);

		//move the cat using the newly calculated speed
		_pCatRef->setPositionX(_pCatRef->getPositionX() + newX);
		_pCatRef->setPositionY(_pCatRef->getPositionY() + newY);

		//check collision with character
		if (_pCatRef->getRect().intersectsRect(_pCharRef->getRect()) )
		{
			//exit this state
			_exitState = true;
			//reduce the character's health
			_pCharRef->reduceHealth(_pCatRef->getBaseAttackDamage());
		}
	}
	else
	{
		//kill this cat
		_pCatRef->setNextCatState(CAT_DYING);
	}
}

void CatState_Base_Attack::onExit()
{
	CatState::onExit();

}

void CatState_Base_Attack::onResume()
{
	CatState::onResume();

	runOnEnter();
}
